import axios, { Method } from 'axios'
import { getToken } from './token-utils'
import nprogress from 'nprogress'
import 'nprogress/nprogress.css'

const wangyi = axios.create({
  // 尚品汇接口前缀是:/sph
  // 网易前缀是：//api
  baseURL: '/api',
  timeout: 4000
})

// 添加请求拦截器
wangyi.interceptors.request.use(
  (config) => {
    // 添加进度条
    nprogress.start()
    // 请求头携带token
    const token = getToken()
    if (token) {
      config.headers.token = token
    }
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

// 添加响应拦截器
wangyi.interceptors.response.use(
  (response) => {
    nprogress.done()
    const res = response.data
    return res
  },
  (error) => {
    // 1.网络错误
    // 2.状态码非2开头
    return Promise.reject(error)
  }
)

// 定义公共接口
export interface IReqLoginRes<T> {
  code: string
  data: T
}

// 封装公共的请求数据的方法
function http<T>(url: string, method: Method, submitData?: unknown) {
  // 将请求方式全部转化为大写
  const newMethod = method.toUpperCase()
  return wangyi.request<T, IReqLoginRes<T>>({
    url,
    method: newMethod,
    data: newMethod === 'POST' || newMethod === 'PUT' || newMethod === 'DELETE' ? submitData : {}, //为post和put的时候传递参数为data
    params: newMethod === 'GET' ? submitData : {} //为get和delete的时候传递的参数为params
  })
}

export default http
